<template>
  <router-view v-if="$route.path === '/login'" />
  <div v-else id="app">
<!--  <div id="app">-->
    <el-container class="app-container">
      <!-- 左侧菜单 -->
      <el-aside width="250px" class="sidebar">
        <div class="logo">
          <h2>{{ appTitle }}</h2>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
        >
          <el-menu-item index="data-collection" v-if="currentUserIdentity === '1'">
            <el-icon><Monitor /></el-icon>
            <span>数据采集</span>
          </el-menu-item>
          <el-menu-item index="data-management">
            <el-icon><Document /></el-icon>
            <span>数据管理</span>
          </el-menu-item>
          <el-menu-item index="task-management">
            <el-icon><List /></el-icon>
            <span>任务管理</span>
          </el-menu-item>
          <el-menu-item index="system-settings" @click="handleRestrictedMenuClick('system-settings')" :disabled="currentUserIdentity !== '1'">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
          <el-menu-item index="admin-management" @click="handleRestrictedMenuClick('admin-management')" :disabled="currentUserIdentity !== '1'">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>

          <!-- 退出登录按钮 -->
          <el-menu-item index="logout" class="logout-item">
            <span style="display: block; float: left; cursor: pointer;" @click="handleUserInfoClick">{{ currentUserName }}</span>
            <div style="display: block; float: right;"  @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              <span style="line-height: 50px;">退出登录</span>
            </div>            
          </el-menu-item>

        </el-menu>
      </el-aside>

      <!-- 右侧内容区 -->
      <el-main class="main-content">
        <router-view v-slot="{ Component }">
          <component :is="Component" />
        </router-view>
      </el-main>
    </el-container>
  </div>
  
  <!-- 修改密码对话框 -->
  <el-dialog
    v-model="showPasswordDialog"
    title="修改密码"
    width="500px"
    :close-on-click-modal="false"
    @close="closePasswordDialog"
  >
    <el-form
      ref="passwordFormRef"
      :model="passwordForm"
      :rules="passwordFormRules"
      label-width="100px"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="passwordForm.oldPassword"
          type="password"
          placeholder="请输入旧密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          type="password"
          placeholder="请输入新密码（至少6位）"
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          v-model="passwordForm.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closePasswordDialog">取消</el-button>
      <el-button type="primary" @click="handleChangePassword" :loading="isLoading">
        确认修改
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";

// 应用标题
const appTitle = ref("信息采集与分析系统（数据采集端）");
import { useRoute, useRouter } from "vue-router";
import { Monitor, Document, List, Setting,SwitchButton } from "@element-plus/icons-vue";
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { loginAPI } from './api/index.js';

const router = useRouter();
const route = useRoute();
const currentUserName = ref(localStorage.getItem('currentUserName'));
const currentUserIdentity = ref(localStorage.getItem('currentUserIdentity'));
console.log('currentUserIdentity:',currentUserIdentity.value)
  
  // 密码修改相关状态
  const showPasswordDialog = ref(false);
  const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  const passwordFormRules = {
    oldPassword: [
      { required: true, message: '请输入旧密码', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '新密码长度在6到20个字符之间', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          // 检查是否包含数字
          if (!/\d/.test(value)) {
            callback(new Error('密码必须包含数字'));
          }
          // 检查是否包含字母（大小写不限）
          else if (!/[a-zA-Z]/.test(value)) {
            callback(new Error('密码必须包含字母'));
          }
          // 检查是否包含特殊字符
          else if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) {
            callback(new Error('密码必须包含特殊字符'));
          }
          else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    confirmPassword: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== passwordForm.value.newPassword) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  };
  const passwordFormRef = ref(null);
  const isLoading = ref(false);
  
  // 处理用户信息点击
  const handleUserInfoClick = () => {
    showPasswordDialog.value = true;
  };
  
  // 重置密码表单
  const resetPasswordForm = () => {
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    };
    if (passwordFormRef.value) {
      passwordFormRef.value.resetFields();
    }
  };
  
  // 关闭密码对话框
  const closePasswordDialog = () => {
    showPasswordDialog.value = false;
    resetPasswordForm();
  };
  
  // 修改密码
  const handleChangePassword = async () => {
    if (!passwordFormRef.value) return;
    
    try {
      await passwordFormRef.value.validate();
      isLoading.value = true;
      
      // 这里需要调用实际的修改密码API
      const result = await loginAPI.updatePassWord({
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      });
      
      if (result && result.code === 0) {
        ElMessage.success('密码修改成功，请重新登录');
        // 清除登录信息并跳转到登录页面
        localStorage.removeItem('isAuthenticated');
        localStorage.removeItem('satoken');
        localStorage.removeItem('currentUserName');
        localStorage.removeItem('currentUserIdentity');
        closePasswordDialog();
        router.push('/login');
      } else {
        ElMessage.error(result?.msg || '密码修改失败');
      }
    } catch (error) {
      if (error.name !== 'Error') {
        // 表单验证失败，不显示错误消息
        return;
      }
      console.error('修改密码失败:', error);
      ElMessage.error('修改密码时发生错误，请稍后重试');
    } finally {
      isLoading.value = false;
    }
  };
const menuMap = {
  "data-collection": "/data-collection",
  "data-management": "/data-management",
  "task-management": "/task-management",
  "system-settings": "/system-settings",
  "admin-management": "/admin-management",
  "taskType-management": "/taskType-management",
  "udp-monitor": "/udp-monitor",
};

// 根据用户身份确定默认页面
const determineDefaultPage = () => {
  const currentUserIdentity = localStorage.getItem('currentUserIdentity');
  // 管理员默认显示数据采集，非管理员默认显示数据管理
  return currentUserIdentity === '1' ? 'data-collection' : 'data-management';
};

// 初始化当前激活的菜单
const activeMenu = ref(determineDefaultPage());

watch(
  () => route.path,
  (path) => {
    if (path.startsWith("/data-collection"))
      activeMenu.value = "data-collection";
    else if (path.startsWith("/data-management"))
      activeMenu.value = "data-management";
    else if (path.startsWith("/task-management"))
      activeMenu.value = "task-management";
    else if (path.startsWith("/system-settings"))
      activeMenu.value = "system-settings";
    else if (path.startsWith("/admin-management"))
      activeMenu.value = "admin-management";
    else if (path.startsWith("/taskType-management"))
      activeMenu.value = "taskType-management";
    else if (path.startsWith("/udp-monitor"))
      activeMenu.value = "udp-monitor";

  },
  { immediate: true }
);


// 处理受限菜单点击
const handleRestrictedMenuClick = (key) => {
  // 如果不是管理员，显示无权限提示
  if (currentUserIdentity.value !== '1') {
    ElMessage.warning('您没有权限访问该功能');
    // 阻止事件冒泡，防止触发@select事件
    event?.stopPropagation?.();
    return;
  }
  
  // 设置菜单点击标记
  sessionStorage.setItem('isFromMenu', 'true');
  router.push(menuMap[key]);
};

const handleMenuSelect = (key) => {
  if (key === 'logout') return; // 防止退出按钮触发路由跳转
  
  // 检查是否为受限菜单且用户无权限
  const restrictedMenus = ['system-settings', 'admin-management'];
  if (restrictedMenus.includes(key) && currentUserIdentity.value !== '1') {
    // 不做任何操作，保持原有选中状态
    return;
  }
  
  // 设置菜单点击标记
  sessionStorage.setItem('isFromMenu', 'true');
  router.push(menuMap[key]);
};


// 退出登录处理
const handleLogout = async () => {
  try {
    // 调用退出接口
    const result = await loginAPI.logOut();
    // 清除本地存储的认证信息（无论接口是否成功）
    localStorage.removeItem('isAuthenticated');
    localStorage.removeItem('satoken');
    localStorage.removeItem('currentUserName');
    localStorage.removeItem('currentUserIdentity');
    console.log('调用退出接口');
    console.log('currentUserName:')
    console.log(localStorage.getItem('currentUserName'))
    console.log('currentUserIdentity:')
    console.log(localStorage.getItem('currentUserIdentity'))
    // 根据接口返回结果显示提示
    if (result?.code === 0) {
      ElMessage.success(result.message || '退出登录成功');
    } else {
      ElMessage.error(result?.message || '退出登录失败');
    }

    // 跳转到登录页
    router.push('/login');

  } catch (error) {
    console.error('退出登录失败:', error);
    ElMessage.error(error.response?.data?.message || '退出登录失败');

    // 确保即使出错也清除认证和跳转
    localStorage.removeItem('isAuthenticated');
    localStorage.removeItem('satoken');
    localStorage.removeItem('currentUserName');
    localStorage.removeItem('currentUserIdentity');
    router.push('/login');
  }
};

// 统一的初始化数据函数
const initAppData = () => {
  // 更新用户名和身份信息
  currentUserName.value = localStorage.getItem('currentUserName');
  currentUserIdentity.value = localStorage.getItem('currentUserIdentity');
  console.log('当前用户名：', currentUserName.value);
  console.log('当前用户身份：', currentUserIdentity.value);
};

// 监听路由变化，当从登录页跳转到其他页面时重新初始化数据
watch(
  () => route.path,
  (newPath, oldPath) => {
    // 当从登录页跳转到其他页面，或者当前页面不是登录页时，重新初始化
    if (oldPath === '/login' || newPath !== '/login') {
      initAppData();
    }
  },
  { immediate: true }
);

onMounted(() => {
  // 页面首次加载时执行初始化
  initAppData();
});

</script>
<style scoped>
.app-container {
  height: 100vh;
}

.sidebar {
  background-color: #304156;
  color: white;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #434a50;
}

.logo h2 {
  margin: 0;
  color: #409eff;
  font-size: 18px;
}

.sidebar-menu {
  border: none;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.logout-item {
  margin-top: auto; /* 将退出按钮推到菜单底部 */
  border-top: 1px solid #434a50;
  display: block;
}

.main-content {
  background-color: #f5f5f5;
  padding: 0;
}
</style>
